<template>
  <view class="container">
    <view class="main">
      <view class="fromLine">
        <view class="fromLine-item">
          <view class="title">
            <text style="color: red;">*</text>联系人
          </view>
          <input class="ipt" placeholder-class="styles" v-model="formLine.real_name" placeholder="请输入联系人" type="text" />
        </view>
        <view class="fromLine-item">
          <view class="title">
            <text style="color: red;">*</text>手机号
          </view>
          <input class="ipt" placeholder-class="styles" maxlength="11" v-model="formLine.phone" placeholder="请输入手机号" type="number" />
        </view>
        <view class="fromLine-item">
          <view class="title">
            <text style="color: red;">*</text>省、市、区/县
          </view>
          <view class="block" @click="handleChoose">
            <view class="address-label">{{addressInfo?addressInfo:'请选择'}}</view>
            <image class="arrow" src="/static/images/arrow.png" mode=""></image>
          </view>
        </view>
        <view class="fromLine-item">
          <view class="title">
            <text style="color: red;">*</text>详细地址
          </view>
          <input class="ipt" type="text" placeholder-class="styles" v-model="formLine.detail" placeholder="请输入详细地址" />
        </view>
      </view>
      <view class="defaultInfo" @click="handleToggle">
        <image class="round-icon" :src="formLine.is_default?'/static/images/roundActive.png':'/static/images/round.png'"
          mode=""></image>
        <text class="default-txt">默认地址</text>
      </view>
    </view>
    <view style="width: 100%;height: 194rpx;"></view>
    <view class="footer">
      <view class="btn" @click="toAdd">
        保存
      </view>
    </view>
    <uv-picker ref="picker" :columns="addressList" @change="change" keyName="n" @confirm="confirm">
    </uv-picker>
  </view>
</template>

<script>
  import reqApi from "../../api/api.js";
  import tools from "../../utils/index.js"
  export default {
    data() {
      return {
        formLine: {
          id: "",
          real_name: "", //联系人
          phone: "", //手机号
          address: {
            province: "",
            city: "",
            district: "",
            city_id: ""
          },
          detail: "",
          is_default: 0, //1默认地址 0 非默认地址
        },
        addressInfo: "",
        provinces: [], //省
        citys: [], //市
        areas: [], //区
        pickerValue: [1, 2, 3],
        defaultValue: [1, 2, 3],
        prevIndex: 0
      }
    },
    onLoad(option) {
      if(option.id){
        this.getDetail(option.id);
        uni.setNavigationBarTitle({
          title: "编辑收货地址"
        })
      }
      this.getCityList();
    },
    computed: {
      addressList() {
        return [this.provinces, this.citys, this.areas];
      }
    },
    methods: {
      getDetail(id){
        reqApi.singleAddress({id}).then(res=>{
          console.log("地址详情", res);
          const {province,city,district,city_id} = res.data;
          res.data.address = {
            province,
            city,
            district,
            city_id
          }
          this.formLine = res.data;
          this.addressInfo = `${province}/${city}/${district}`;
        })
      },
      getCityList() {
        reqApi.cityList({}).then(res => {
          console.log("城市数据", res);
          const {
            data
          } = res;
          console.log('获取的数据：', res);
          this.provinces = data.sort((left, right) => (Number(left.v) > Number(right.v) ? 1 : -1));
          console.log("provinces1", this.provinces);
          this.handlePickValueDefault();
        })
      },
      toAdd(){
        console.log("formLine", this.formLine);
        if (!this.formLine.real_name) {
          uni.showToast({
            title: "请输入联系人",
            icon: 'none',
            mask: true,
            duration: 1500,
          })
          return
        }
        if (!this.formLine.phone) {
          uni.showToast({
            title: "请输入手机号",
            icon: 'none',
            mask: true,
            duration: 1500,
          })
          return
        }
        if (!tools.checkPhone(this.formLine.phone)) {
          uni.showToast({
            title: "手机号格式错误",
            icon: 'none',
            mask: true,
            duration: 1500,
          })
          return
        }
        if (!this.addressInfo) {
          uni.showToast({
            title: "请选择省市区",
            icon: 'none',
            mask: true,
            duration: 1500,
          })
          return
        }
        if (!this.formLine.detail) {
          uni.showToast({
            title: "请输入详细地址",
            icon: 'none',
            mask: true,
            duration: 1500,
          })
          return
        }
        reqApi.setAddress(this.formLine).then(res=>{
          uni.showToast({
            title: this.formLine.id?"编辑成功":"添加成功",
            icon: 'none',
            mask: true,
            duration: 1500,
          })
          setTimeout(()=>{
            uni.navigateBack({delta: 1})
          }, 1500)
        })
      },
      handleChoose() {
        this.$refs.picker.open();
        this.handlePickValueDefault();
      },
      confirm(e) {
        console.log('确认选择的地区：', e);
        this.formLine.address.province = e.value[0].n;
        this.formLine.address.city = e.value[1].n;
        this.formLine.address.district = e.value[2].n;
        this.formLine.address.city_id = e.value[1].v;
        this.addressInfo = `${e.value[0].n}/${e.value[1].n}/${e.value[2].n}`;
      },
      handlePickValueDefault() {
        console.log("pickerValue", this.pickerValue)
        // 设置省
        this.pickerValue[0] = this.provinces.findIndex(item => Number(item.v) === this.defaultValue[0]);
        // 设置市
        this.citys = this.provinces[this.pickerValue[0]]?.c || [];
        this.pickerValue[1] = this.citys.findIndex(item => Number(item.v) === this.defaultValue[1]);
        // // 设置区
        this.areas = this.citys[this.pickerValue[1]]?.c || [];
        this.pickerValue[2] = this.areas.findIndex(item => Number(item.v) === this.defaultValue[2]);
        // 重置下位置
        this.$refs.picker.setIndexs([this.pickerValue[0], this.pickerValue[1], this.pickerValue[2]], true);
        console.log("省", this.provinces);
        console.log("市", this.citys);
        console.log("区", this.areas);
      },
      change(e) {
        if (this.loading) return;
        console.log("切换", e);
        const {
          columnIndex,
          index
        } = e
        // 改变了省
        if (columnIndex === 0) {
          this.prevIndex = index;
          this.citys = this.provinces[index]?.c || []
          this.areas = this.citys[0]?.c || []
          this.$refs.picker.setIndexs([index, 0, 0])
        } else if (columnIndex === 1) {
          this.areas = this.citys[index]?.c || []
          this.$refs.picker.setIndexs([this.prevIndex, index, 0])
        }
      },
      handleToggle() {
        this.formLine.is_default = !this.formLine.is_default;
      }
    }
  }
</script>

<style lang="scss" scoped>
    .footer{
      padding: 50rpx;
      box-sizing: border-box;
      background: #fff;
      position: fixed;
      width: 100%;
      bottom: 0;
      .btn{
        width: 100%;
        height: 88rpx;
        background: linear-gradient( 270deg, #FF3C21 0%, #EA7222 100%);
        box-shadow: 0rpx 16rpx 20rpx 0rpx rgba(9,124,105,0.2);
        border-radius: 48rpx;
        font-family: PingFang SC, PingFang SC;
        font-weight: bold;
        font-size: 32rpx;
        color: #FFFFFF;
        text-align: center;
        line-height: 88rpx;
      }
    }
  .defaultInfo {
    display: flex;
    align-items: center;
    margin-top: 30rpx;

    .round-icon {
      width: 40rpx;
      height: 40rpx;
      margin-right: 20rpx;
    }

    .default-txt {
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 24rpx;
      color: #333333;
    }
  }

  .block {
    display: flex;

    .address-label {
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 28rpx;
      color: #666666;
      flex: 1;
    }

    .arrow {
      width: 40rpx;
      height: 40rpx;
    }
  }

  .container {
    .main {
      padding: 30rpx;
      box-sizing: border-box;

      .fromLine {
        padding: 0 30rpx;
        border-radius: 30rpx;
        background: #fff;

        .fromLine-item {
          height: 190rpx;
          border-bottom: 2rpx solid #eee;
          padding: 30rpx 0;
          box-sizing: border-box;
          display: flex;
          flex-direction: column;
          justify-content: space-between;

          .title {
            font-family: PingFang SC, PingFang SC;
            font-weight: 400;
            font-size: 32rpx;
            color: #333333;
          }

          .ipt {
            font-family: PingFang SC, PingFang SC;
            font-weight: 400;
            font-size: 28rpx;
            color: #666666;
          }

          .styles {
            font-family: PingFang SC, PingFang SC;
            font-weight: 400;
            font-size: 28rpx;
            color: #666666;
          }
        }
      }
    }
  }
</style>